package state;

import movgen.BitUtil;
import movgen.EnPassant;
import movgen.Util;

public class Fen {
	 /**
	 * Generates a FEN equivalent of the given state.
	 *
	 * @return 		the FEN equivalent string
	 */
	public static String toFEN(GameState state)
	{
		StringBuffer FEN = new StringBuffer(70);
		long[] gameboard = getGameBoard(state.bitboard);
		char[] board = BitUtil.bitboardsToCharBoard(gameboard);
		
		int i,j,k,e;
		
		for(i=0; i<8; i++)
		{
			e = 0; // No. of empty squares
			for(j=0; j<8; j++)
			{
				k = i*8+j; // Array index
				if(board[k] != '-')
				{
					if( e > 0 )
					{
						FEN.append(e);
						e = 0;
					}
					FEN.append(board[k]);
				}
				else
				{
					e++;
				}
			}
			if( e > 0 )
			{
				FEN.append(e);
			}
			FEN.append('/');
		}
		
		FEN.deleteCharAt(FEN.length()-1); // to remove the trailing '/'
		FEN.append(' ');
		if (state.color==GameState.WHITE) FEN.append('w'); else FEN.append('b');
	
		FEN.append(' ');
		
		FEN.append(state.castlingToString());
		FEN.append(' ');
		int epSquare = EnPassant.getEPSquare(state.flags);
		
		FEN.append(epSquare == 0 ? '-' : Util.toCoOrdinate( (byte)(63 - epSquare)));
		return FEN.toString();
	}
 
  private static long[] getGameBoard(long[] bb) {
	// TODO Auto-generated method stub
	 long[] board = new long[12];
	 for (int i=0; i< 12; i++) board[i]=bb[i];
	 return board;
}
}
